<template>
  <a-modal
    :title="title"
    centered
    :width="980"
    :maskClosable="false"
    :destroyOnClose="true"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="cancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :model="form" ref="formRef" >
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item
              label="菜单名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
              name="name"
              :rules="[{ required: true, message: '请输入菜单名称！' },{ max:95, message: '最多可输入95个字符！'}]"
            >
              <a-input :maxLength="95" placeholder="请输入菜单名称" v-model:value="form.name" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="菜单编号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
              name="code"
              :rules="[{ required: true, message: '请输入菜单编号！' },{ max:50, message: '最多可输入50个字符！'}]"
            >
              <a-input :maxLength="50" placeholder="请输入菜单编号" autocomplete="off" v-model:value="form.code" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item
              label="所属应用"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
              name="application"
              :rules="[{ required: true, message: '请选择所属应用！' }]"
            > 
            <a-select
                    placeholder="请选择所属应用"
                    :disabled="appDisabled"
                    v-model:value="form.application"
                  >
                    <a-select-option
                      v-for="(item, index) in appData"
                      @click="changeApplication(item.code)"
                      :key="item.id"
                      :value="item.code"
                      >{{ item.name }}</a-select-option
                    >
                  </a-select>
              
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="菜单层级"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              name="type"
              :rules="[
                { required: true, message: '请输入菜单层级！' }
              ]"
            >
               <a-radio-group v-model:value="form.type">
                <a-radio v-for="(item,index) in menuType" :key="index" :value="item.code" @click="meneTypeFunc(item.code)" >{{ item.value }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
          <div v-show="pidShow">
            <a-form-item  label="父级菜单" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-tree-select
                placeholder="请选择父级菜单"
                style="width: 100%; "
                :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
                :treeData="menuTreeData"
                treeDefaultExpandAll
                v-model:value="form.pid"
                @change="setPid"
              >
                <template #title="{ id }">
                  <span>{{ id }}</span>
                </template>
              </a-tree-select>
            </a-form-item>
          </div>
          <div v-if="redirectShow">
            <a-form-item  :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback :rules="[{ max:95, message: '最多可输入95个字符！'}]">
                <template #label >
                  <a-tooltip title="如需打开首页加载此目录下菜单，请填写加载菜单路由，设为首页后其他设置的主页将被替代">
                    <QuestionCircleOutlined class="msy-atooltip" />
                  </a-tooltip>&nbsp;
                  重定向
                </template>
              <a-input :maxLength="95" placeholder="请输入重定向" v-model:value="form.redirect" />
            </a-form-item>
            </div>
          </a-col>
       
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :rules="[
                { required: true, message: '请选择打开方式！', trigger: 'change' }
              ]"
            >
              <template #label >
                  <a-tooltip title="按钮：无，菜单：内链、外链、组件">
                    <QuestionCircleOutlined class="msy-atooltip" />
                  </a-tooltip>&nbsp;
                  打开方式
                </template>
              <a-radio-group v-model:disabled="openTypeDisabled" v-model:value="form.openType">
                <a-radio v-for="(item,index) in openTypeData" :key="index" :value="item.code" @change="meneOpenTypeFunc(item.code)" >{{ item.value }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          </a-row>
          <a-divider ></a-divider>
          
        <a-row :gutter="24">
          <a-col :md="12" :sm="24" v-if="componentShow">
            <div  >
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              name="component"
              :rules="[
                { required: componentRequired, message: '请输入前端组件！' },{ max:95, message: '最多可输入95个字符！'}
              ]"
            >
              <template #label >
                  <a-tooltip title="前端vue组件 views文件夹下路径，例：system/menu/index。注：目录级填写：RouteView(不带面包屑)，PageView(带面包屑)，菜单级内链打开http链接填写：Iframe">
                    <QuestionCircleOutlined class="msy-atooltip" />
                  </a-tooltip>&nbsp;
                  前端组件
                </template>
              <a-input :maxLength="95" placeholder="请输入前端组件" :disabled="componentDisabled" v-model:value="form.component" />
            </a-form-item>
            </div>
          </a-col>
      
          <a-col :md="12" :sm="24">
            <div v-if="routerShow">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
              name="router"
              :rules="[
                { required: routerRequired, message: '请输入路由地址！' },{ max:95, message: '最多可输入95个字符！'}
              ]"
            >
              <template #label >
                  <a-tooltip title="浏览器显示的URL，例：/menu，对应打开页面为菜单页面">
                    <QuestionCircleOutlined class="msy-atooltip" />
                  </a-tooltip>&nbsp;
                  路由地址
                </template>
              <a-input :maxLength="95" placeholder="请输入路由地址" v-model:value="form.router" />
            </a-form-item>
            </div>
          <div v-if="permissionShow">
            <a-form-item label="权限标识" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback :rules="[
                { required: permissionRequired, message: '请输入权限标识！' },{ max:85, message: '最多可输入85个字符！'}
              ]">
              <a-input :maxLength="85" placeholder="请输入权限标识" v-model:value="form.permission" />
            </a-form-item>
          </div>
          </a-col>
        </a-row>
        
        <a-row :gutter="24">
          <a-col :md="12" :sm="24" v-if="linkShow">
            <div  >
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
              :rules="[{ required: linkRequired, message: '请选择内外链地址！' },{ max:95, message: '最多可输入95个字符！'}]"
            >
              <template #label >
                  <a-tooltip title="当选择了需要内链或外链打开的选项，此处输入要打开的链接地址，例：http://www.msy.cn">
                    <QuestionCircleOutlined class="msy-atooltip" />
                  </a-tooltip>&nbsp;
                  内外链地址
                </template>
              <a-input
                :disabled="linkDisabled"
                placeholder="请选择内外链地址"
                :maxLength="95"
                autocomplete="off"
                v-model:value="form.link"
              />
            </a-form-item>
            </div>
          </a-col>
          <a-col :md="12" :sm="24">
            <div v-if="iconShow" >
            <a-form-item label="图标" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                :maxLength="35"
                placeholder="请输入图标"
                :disabled="true"
                v-model:value="form.icon"
              >
              <template #addonAfter >
              <a-tooltip title="设置">
                    <SettingOutlined @click="openIconSele()" />
                  </a-tooltip>
                  </template>
                  <template #addonBefore >
                  <a-tooltip title="清除">
                    <RestOutlined @click="clearIconSele()" />
                  </a-tooltip>
                  </template>
              </a-input>
            </a-form-item>
            </div>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <template #label >
                  <a-tooltip title="系统权重：菜单可分配给任何角色，业务权重：菜单对超级管理员不可见">
                    <QuestionCircleOutlined class="msy-atooltip" />
                  </a-tooltip>&nbsp;
                  权重
                </template>
              <a-radio-group v-model:value="form.weight">
                <a-radio v-for="(item,index) in weightData" :key="index" :value="item.code"  >{{ item.value }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="是否可见" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-switch checked-children="是" un-checked-children="否" v-model:checked="form.visible" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
           <a-form-item label="排序" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input-number style="width: 100%; " id="inputNumber" placeholder="请输入排序" v-model:value="form.sort" :min="1" :max="110" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
           <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                :maxLength="205"
                placeholder="请输入备注"
                v-model:value="form.remark"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>

    <a-modal
      centered
      :width="980"
      :destroyOnClose="true"
      :visible="visibleIcon"
      @cancel="handleCancelIcon"
      footer=""
      :mask="false"
      :closable="false"
    >
      <icon-selector ref="toform" :currentSelected="currentSelectedIcon" @change="handleIconChange"/>
    </a-modal>
  </a-modal>
</template>

<script lang='ts'>
import { defineComponent, PropType, reactive, toRefs, ref, computed, watch, onMounted,nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from '@/store'
import { formRules } from '@/utils/validator'
import { RuleObject, ValidateErrorEntity } from 'ant-design-vue/es/form/interface'
import { getOrgList, sysPosList, sysUserAdd } from '@/api/system/user'
import { sysDictTypeDropDown } from '@/api/system/dict'
import { getAppList } from '@/api/system/app'
import { IconSelector } from '@/components'
import { SysMenuList, getMenuTree, sysMenuAdd, sysMenuEdit, sysMenuDetail} from '@/api/system/menu'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { uniqueId } from 'lodash'
interface extIdsType {
  key: string
  orgId: unknown
  posId: unknown
}
export default defineComponent({
  name: 'operationFrom',
  components: {
    IconSelector
  },
  props: {
    title: {
      type: String,
      default: ''
    }
  },
  emits: ['refresh'],
  setup(props, ctx) {
    const formRef = ref<any>(null)
    const toform = ref<any>(null)
    const router = useRouter()
    const store = useStore()
    const state = reactive({
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      // 机构行样式
      labelCol_JG: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol_JG: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      add: false,
      visible: false,
      confirmLoading: false,
      visibleIcon: false,
      // 图标组件
        currentSelectedIcon: 'pause-circle',
      /** 打开方式 */
      openTypeDisabled: false,
      /** 菜单类型 */
      menuType: [],
      /** 权重 */
      weightData: [],
      /** 打开方式 */
      openTypeData: [],
      /** 所属应用 */
      appData: [],
      type:'',
      menuTreeData: [],
      /** 重定向 */
      redirectShow: true,
      appDisabled: false,
        componentShow: true,
        linkRequired:true,
        componentDisabled: false,
        linkDisabled: false,
        componentRequired: true,
        routerRequired: true,
        routerShow: true,
        iconShow: true,
        linkShow: true,
        openTypeShow: true,
        /** 父级菜单 */
        pidShow: true,
        permissionShow: true,
        permissionRequired: true,
        openType:'',
      detailData: {} as any,
      menuId:null,
      form: {
        name: '',
        code: '',
        application: null,
        openType: '',
        pid:'0',
        redirect: '',
        type:'1',
        component: '',
        permission: '',
        weight: '2',
        link: '',
        icon: '',
        router: '',
        visible: true,
        sort: 100,
        remark:''
      },
      birthdayString: [] as string[]
    })
    /**详情监听 */
    watch(
      () => state.detailData,
      (v) => {
        console.log('v', v);

        changeApplication(v.application)
        state.openType = v.openType.toString();
        meneTypeFunc(v.type.toString())
        if (v.pid === '0') {
           // 再不能切换应用
          state.appDisabled = false
        } else {
          state.appDisabled = true
        }
        // 图标
        state.currentSelectedIcon = v.icon;

        state.menuId = v.id;
        state.form = {
          name: v.name,
          code: v.code,
          application: v.application.toString(),
          openType: v.openType.toString(),
          redirect: v.redirect,
          component: v.component,
          permission: v.permission,
          weight: v.weight.toString(),
          type: v.type.toString(),
          link: v.link,
          icon: v.icon,
          pid: v.pid,
          router: v.router,
          visible: v.visible == 'Y' ? true : false,
          sort: v.sort,
          remark: v.remark,
        }
      }
    )
    onMounted(() => {
      getSysApplist();
      meneTypeFunc('1')
      // 菜单层级
      sysDictTypeDropDown({ code: 'menu_type' }).then((res) => {
        state.menuType = res
      })
      // 打开方式
      sysDictTypeDropDown({ code: 'open_type' }).then((res) => {
        state.openTypeData = res
      })
      
      // 权重
      sysDictTypeDropDown({ code: 'menu_weight' }).then((res) => {
        state.weightData = res
      })
      
      state.form.type = '1';
      state.form.weight = '2';
      state.form.visible = true;
      state.form.pid = '0';
      
      console.log('onMounted-menu');
    })
    /** 打开图标弹框 */
    function openIconSele () {
        state.visibleIcon = true
        // console.log(toform);
          nextTick(()=>{
            if(state.iconShow){
              toform.value.selectedIcon = state.currentSelectedIcon
            }
        })
        
        
      }
      /** 清除图标 */
      function clearIconSele () {
        state.form.icon = '';
      }
      /** 选择图标 */
      function handleIconChange (icon) {
        state.form.icon = icon;
        state.visibleIcon = false
      }
      /** 取消-关闭图标弹框 */
      function handleCancelIcon () {
        state.visibleIcon = false
      }

    /** 获取系统应用列表 */
    function getSysApplist () {
        return getAppList().then((res) => {
            state.appData = res;
        })
      }
      /**
       * 选择父级
       */
      function setPid (value) {
        state.form.pid = value
      }

    /** 菜单层级 */
    function meneTypeFunc(type){
       if (type == '0' || type == '1') {
          // 内外链地址显示，给空值
          state.linkShow = true
          // state.form.link = [];
          state.form.link = '';
          // 图标选择显示
          state.iconShow = true
          // 路由必填，设置空值，并显示
          state.routerRequired = true
          state.form.router = '';
          state.routerShow = true
          // 权限标识框隐藏，选填，给空值
          state.permissionShow = false
          state.permissionRequired = false
          state.form.permission = ''
          // 打开方式设置为组件 ，禁用选择方式
          state.openType = state.openType==''?'1':state.openType
          state.form.openType = state.openType
          state.openTypeDisabled = false
    }
    if (type == '0') {
          // 重定向展示，并给空
          state.redirectShow = true
          // state.form.redirect = [];
          state.form.redirect = '';
          // 组件默认为显示，设置可输入，给默认组件 PageView，验证必填
          state.componentShow = true
          state.componentDisabled = false
          state.form.component = 'PageView';
          state.componentRequired = true
          // 父级初始化顶级，并将其隐藏
          state.form.pid = '0';
          state.pidShow = false
        } else {
          // eslint-disable-next-line eqeqeq
          if (type == '1') {
            // 组件可以手输，取消值
            state.componentDisabled = false
            state.form.component = ''
          }
          // 重定向输入隐藏，并给空值
          state.redirectShow = false
          state.form.redirect = ''
          // 父级选择放开
          state.pidShow = true
        }
        if (type == '2') {
          state.componentShow = false;
          // 组件设置不填，不可输入，并给空（手输的跟设置的）
          state.componentRequired = false
          state.componentDisabled = true
          // state.form.component=[]
          state.form.component= ''
          // 路由选填，设置空值，并隐藏
          state.routerRequired = true
          state.form.router=''
          state.routerShow = false
          // 内外链地址隐藏，给空值
          state.linkShow = false
          state.form.link=''
          // 权限标识框显示，必填，给空值
          state.permissionShow = true
          state.permissionRequired = true
          state.form.permission=''
          // 图标选择隐藏,并给空
          state.iconShow = false
          state.form.icon= ''
          // 打开方式设置为无 ，禁用选择方式
          state.openType = '0'
          state.form.openType = state.openType='0'
          state.openTypeDisabled = true
          // 取消icon
          state.form.icon ='';
        }else{
          state.componentShow = true;
        }

        meneOpenTypeFunc(state.openType)
    }
    /**
       * 选择打开方式执行方法
       */
     function meneOpenTypeFunc (openType) {
          console.log('openType', openType, 918, state.form.type);
          state.form.openType = openType;
          if (state.form.type == '0') {
            if(openType == '0'){
              state.componentShow = false;
              state.linkShow = false;
            }else{
              
              state.componentShow = true;
              state.linkShow = true;
            }
            if(openType == '1'){
              state.componentDisabled = false;
              state.linkShow = false;
            }
          }
          if (state.form.type == '1') {
            if(openType == '0'){
                state.componentShow = false;
              }
              if(openType == '1'){
                state.componentDisabled = false;
                state.componentShow = true;
              }
          }
           if (state.form.type == '0') {
             if(openType == '1'){
               state.form.component = 'PageView';
             }
            if(openType == '0' || openType == '1'){
                
                state.linkShow = false;
              }else{
                state.linkShow = true;
              }
           }
         // eslint-disable-next-line eqeqeq
         if (openType == '2' || openType == '3') {
           // 点击内外链的时候保留原值，其他清空
           if (state.linkDisabled === false) {
            //  state.form.link=[];
            state.form.link='';
           }
            // 设置内外链可手输，加验证
           state.linkDisabled = false
           state.componentShow = false;
           state.linkShow = true;
           state.linkRequired = true
         } else {
            // 设置内外链不可手输，取消值，取消验证
            state.linkDisabled = true
            state.linkShow = false
            // state.form.link=[]
            state.form.link=''
            state.linkRequired = false
         }
         // 另起一个分支
        // eslint-disable-next-line eqeqeq
        if (openType == '3') {
          state.componentRequired = false
          state.componentDisabled = true
          // state.form.component=[]
          state.form.component='';
          // state.linkShow = false;
          if(state.form.type == '1' || state.form.type == '0'){
            
            state.componentShow = false;
          }
          state.linkShow = true;
        } else {
          
          state.componentRequired = true
          // eslint-disable-next-line eqeqeq state.form.type == '1' || 
          if (state.form.type == '2') {
            state.form.component='';
          } else {
            if(openType == '0'){
              state.form.component='';
            }else{
              // state.form.component=[]
              state.form.component='';
              state.form.component='PageView'
            }
          }
          // eslint-disable-next-line eqeqeq
          if (openType == '2') {
            state.linkShow = true;
            // 组件设置为 iframe
            state.componentShow = true;
            // state.form.component=[]
            state.form.component=''
            state.form.component='Iframe'
          }
        }
        // 按钮
        if (state.form.type == '2') {
          // eslint-disable-next-line eqeqeq
          state.componentShow = false;
          if (openType == '0') {
            state.componentRequired = false
            state.routerRequired = false
            
          }
        }
        if (openType == '2' || openType == '3') {

            state.componentShow = false;
        }
      }

    function changeApplication (value) {
        getMenuTree({ 'application': value }).then((res) => {
            // state.form.pid = [];
            state.menuTreeData = [{
              'id': '-1',
              'parentId': '0',
              'title': '顶级',
              'value': '0',
              'pid': '0',
              'children': res
            }]
        })
      }
    /** 提交 */
    function handleSubmit() {
      state.confirmLoading = true
      console.log('state.menuId',state.menuId, state.form);
       if (state.form.visible) {
              state.form.visible = 'Y'
            } else {
              state.form.visible = 'N'
            }
      formRef.value
        .validate()
        .then(() => {
          if(state.menuId == null){
            sysMenuAdd(state.form)
              .then((res) => {
                message.success('新增成功')
                state.confirmLoading = false
                // state.visible = false
                cancel();
                ctx.emit('refresh')
              })
              .catch((err) => {
                state.confirmLoading = false
              })
          
        }else{
            let data = Object.assign({},state.form,{id:state.menuId});
            sysMenuEdit(data)
              .then((res) => {
                message.success('编辑成功')
                state.confirmLoading = false
                // state.visible = false
                cancel();
                ctx.emit('refresh')
              })
              .catch((err) => {
                state.confirmLoading = false
              })
         
        }
           })
          .catch((err) => {
            state.confirmLoading = false
            // console.log('nopass', err)
          })
    }
    /**
     * 重置表单
     */
    function resetForm() {
      state.menuId = null;
      state.openType = '';
      state.form = {
        name: '',
        code: '',
        application: null,
        openType: '',
        type:'1',
        redirect: '',
        component: '',
        permission: '',
        weight: '2',
        link: '',
        icon: '',
        router: '',
        visible: true,
        sort: 100,
        remark:''
        
      }
    }
    /**
     * 退出
     */
    const cancel = () => {
      state.appDisabled = false;
      resetForm()
      meneTypeFunc('1')
      //   formRef.value.resetFields()
      state.visible = false
    }
    /**
     * 禁用日期
     */
    const disabledDate = (current) => {
      return current && current > dayjs().endOf('day') //当天之前的不可选，包括当天
      // return current < dayjs().subtract(1, 'day')// 当天之前的不可选，不包括当天
    }

    /**
     * 删除
     */
    function remove(key) {
      state.form.sysEmpParam.extIds.splice(
        state.form.sysEmpParam.extIds.findIndex((v) => v.key == key),
        1
      )
    }
    /**
     * handleChange
     */
    function handleChange() {}
   
    const validatePass = async (rule: RuleObject, value: string) => {
      if (value === '') {
        return Promise.reject('请输入密码')
      } else {
        if (state.form.confirm !== '') {
          formRef.value.validateField('checkPass')
        }
        return Promise.resolve()
      }
    }
    const validatePass2 = async (rule: RuleObject, value: string) => {
      if (value === '') {
        return Promise.reject('请再次输入密码')
      } else if (value !== state.form.password) {
        return Promise.reject('请确认两次输入密码的一致性！')
      } else {
        return Promise.resolve()
      }
    }
    return {
      ...toRefs(state),
      props,
      formRef,
      toform,
      formRules,
      handleSubmit,
      validatePass,
      validatePass2,
      handleChange,
      disabledDate,
      changeApplication,
      clearIconSele,
      setPid,
      handleIconChange,
      handleCancelIcon,
      openIconSele,
      meneOpenTypeFunc,
      meneTypeFunc,
      cancel,
      remove
    }
  }
})
</script>

<style lang="scss">
  ::v-deep(.ant-form-item label > .anticon){
    vertical-align: text-bottom!important;
  }
  .msy-atooltip{
      vertical-align: text-bottom!important;
  }
</style>